import { ReactNode, useContext, useLayoutEffect, useState } from 'react';

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
import { Slice } from '@reduxjs/toolkit/src/createSlice.ts';

import { myContext } from '@/core/injectContext.ts';

export const ReducerAdapter = <
  State,
  CaseReducers,
  Name,
  ReducerPath,
  Selectors,
>({
  slice,
  children,
  removeAfterUnmountAll = false,
}: {
  children: ReactNode;
  slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors>;
  /** Не подразумевается, что будет изменяться. НЕ МЕНЯТЬ!*/
  removeAfterUnmountAll?: boolean;
}) => {
  const { updateRedux, removeSlice } = useContext(myContext);
  const [isInit, setIsInit] = useState(false);
  const [needRemove] = useState(removeAfterUnmountAll);

  useLayoutEffect(() => {
    updateRedux(slice);
    setIsInit(true);
    return () => {
      slice.getInitialState;
      needRemove && removeSlice(slice);
    };
  }, [needRemove, removeSlice, slice, updateRedux]);

  if (!isInit) {
    return null;
  }

  return children;
};
